#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Datetime: 2022/9/23 11:52
# @Author  : CHENWang
# @Site    : 
# @File    : others.py
# @Software: PyCharm

"""
脚本说明: 从一些小众网站获取数据
"""

import pandas as pd
import requests
import json
from quant_researcher.quant.project_tool.time_tool import timestamp_to_str
from quant_researcher.quant.project_tool.wrapper_tools.common_wrappers import deco_retry


@deco_retry(retry=50, retry_sleep=15)
def get_btc126_usdt_premium():
    """
    从https://history.btc126.com/usdt/ 获取usdt场外兑人民币折溢价数据, 网站记录的是okex上的USDT的价格

    :return:
    """
    header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'}
    url = 'https://history.btc126.com/usdt/api.php'
    requests_session = requests.Session()
    requests_session.trust_env = False  # 不走VPN代理
    res = requests_session.get(url, headers=header, timeout=15)
    df = pd.DataFrame(json.loads(res.content)['data'])
    df['premium'] = (df['usdt'].astype(float) - df['usd'].astype(float)) / df['usd'].astype(float)

    return df


@deco_retry(retry=50, retry_sleep=15)
def get_feixiaohao_usdt_premium(period='30day'):
    """
    从https://www.feixiaohaozh.info/data/stable.html 获取usdt场外兑人民币折溢价数据, 网站记录的是okex 和币安上的USDT的价格

    :param period: 支持 '30day', '7day', '24h'
    :return:
    """
    header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'}
    url = f'https://dncapi.gomynft.com/api/v1/coin/usdt/rate/trend/{period}?webp=1'
    res = requests.get(url, headers=header, timeout=15)
    df = pd.DataFrame(json.loads(res.content)['data']['kline'])
    df = df.iloc[:, :2]
    df.columns = ['timestamp', 'usdt']
    df['datetime'] = df['timestamp'].apply(timestamp_to_str, fmt='%Y-%m-%d %H:%M:%S', tz_str='+0000')
    df['date'] = df['timestamp'].apply(timestamp_to_str, fmt='%Y-%m-%d', tz_str='+0000')
    df.drop_duplicates(subset=['timestamp'], inplace=True)
    return df


if __name__ == '__main__':
    # 测试get_btc126_usdt_premium
    get_btc126_usdt_premium()

    # 测试get_feixiaohao_usdt_premium
    get_feixiaohao_usdt_premium(period='24h')
